package com.huihui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.huihui.R;
import com.huihui.adapter.MineZanAdapter;
import com.huihui.bean.Goods;
import com.huihui.datamanager.AppManager;
import com.huihui.eventbus.PublicRefrash;
import com.huihui.fragment.BaseFragment;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.huihui.widget.SwipeRecyclerView;
import com.huihui.widget.footerView.SimpleFooterView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by Administrator on 2018/8/15.
 * 超值
 */

public class GoodsSeachFragment extends BaseFragment {

    private SwipeRecyclerView recyclerView;
    private int pageIndex = 1;
    private int pageNum = 10;
    private MineZanAdapter adapter;
    private List<Goods> mList = new ArrayList<>();
    private Goods mGoods;
    private LinearLayout inputLayout;
    private EditText inputTxt;
    private String keyWords;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news,container,false);
        EventBus.getDefault().register(this);
        inputLayout = view.findViewById(R.id.inuput_layout);
        inputTxt = view.findViewById(R.id.input_text);
        initView(view);
        initData();
        initListener();
        return view;
    }

    private void initListener() {
        recyclerView.setOnLoadListener(new SwipeRecyclerView.OnLoadListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                initData();
            }

            @Override
            public void onLoadMore() {
                pageIndex ++;
                initData();
            }
        });
        recyclerView.getRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                hideInputLayout();
            }
        });
        inputTxt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    String content = v.getText().toString();
                    addProductComment(content, 0, mGoods);
                }
                return false;
            }
        });
        adapter.addOnDianZanListener(new MineZanAdapter.onDianZanListener() {
            @Override
            public void onClick(int position) {
                mGoods = mList.get(position);
                if (mGoods.getIs_like() == 0) {
                    addZan(mGoods);

                } else {
                    removeZan(mGoods);
                }
            }
        });
    }
    private void hideInputLayout() {
        inputTxt.getText().delete(0, inputTxt.getText().toString().length());
        inputTxt.clearFocus();
        inputLayout.setVisibility(View.GONE);
    }
    public void setKeyWord(String keyWord){
        this.keyWords = keyWord;
        pageIndex = 1;
        initData();
    }
    private void initData() {
        OkHttpRequest.getInstance().productSearch(HttpContants.search, keyWords, 10, pageIndex, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
                recyclerView.setRefreshing(false);
            }

            @Override
            public void onResponse(String response) {
                recyclerView.setRefreshing(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if(jsonObject != null && jsonObject.has(HttpContants.DATA)){
                        List<Goods> list = AppManager.getGson().fromJson(jsonObject.getString(HttpContants.DATA),new TypeToken<List<Goods>>(){}.getType());
                        if(list != null){
                            if(pageIndex == 1){
                                mList.clear();
                                mList.addAll(list);
                                adapter.notifyDataSetChanged();
                            }else{
                                recyclerView.setLoadMoreEnable(false);
                                mList.addAll(list);
                                adapter.notifyDataSetChanged();
                            }
                            if (list.size() < 10){
                                recyclerView.setLoadMoreEnable(false);
                            }else{
                                recyclerView.setLoadMoreEnable(true);
                            }
                        }else{
                            recyclerView.setLoadMoreEnable(false);
                        }
                    }else{
                        recyclerView.setLoadMoreEnable(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initView(View view) {
        recyclerView = (SwipeRecyclerView) view.findViewById(R.id.recycler);
        recyclerView.getSwipeRefreshLayout()
                .setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        setRecycleView(recyclerView);
        recyclerView.setRefreshing(true);

        adapter = new MineZanAdapter(getActivity(),mList);
        recyclerView.setAdapter(adapter);
    }

    public void setRecycleView(SwipeRecyclerView recyclerView){
        //set layoutManager
        recyclerView.getRecyclerView().setLayoutManager(new LinearLayoutManager(getActivity()));
        //设置emptyView
//        TextView textView = new TextView(getActivity());
//        textView.setText("没有更多数据");
//        recyclerView.setEmptyView(textView);

        //设置footerView
        recyclerView.setFooterView(new SimpleFooterView(getActivity()));
        //设置去除footerView 的分割线
//        recyclerView.getRecyclerView().addItemDecoration(new RecyclerView.ItemDecoration() {
//            @Override
//            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
//                super.onDraw(c, parent, state);
//                Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//                paint.setColor(0xFFEECCCC);
//
//                Rect rect = new Rect();
//                int left = parent.getPaddingLeft();
//                int right = parent.getWidth() - parent.getPaddingRight();
//                final int childCount = parent.getChildCount() - 1;
//                for (int i = 0; i < childCount; i++) {
//                    final View child = parent.getChildAt(i);
//
//                    //获得child的布局信息
//                    final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
//                    final int top = child.getBottom() + params.bottomMargin;
//                    final int itemDividerHeight = 1;//px
//                    rect.set(left + 50, top, right - 50, top + itemDividerHeight);
//                    c.drawRect(rect, paint);
//                }
//            }
//        });
    }

    private void addProductComment(String content, int parentCommentId, Goods goods) {
        OkHttpRequest.getInstance().addProductComment(HttpContants.product_addComment, AppManager.getUserInfo().getUser_id(), goods.getProd_id(),
                parentCommentId, content, new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        hideInputLayout();
                        pageIndex = 1;
                        initData();
                    }
                });

    }
    private void removeZan(Goods goods) {
        int class_id = 0;
        int comment_id = 0;
        long relation_id = goods.getProd_id();

        OkHttpRequest.getInstance().removeCollection(HttpContants.removeCollection, AppManager.getUserInfo().getUser_id(),
                relation_id, class_id, comment_id, new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject productObject = new JSONObject(response);
                            if (productObject != null && productObject.has(HttpContants.STATE) && productObject.getInt(HttpContants.STATE) == 10000) {

                                mGoods.setCollection_num(mGoods.getCollection_num() - 1);
                                mGoods.setIs_like(0);
                                adapter.notifyDataSetChanged();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    private void addZan(Goods goods) {
        //商品
        int class_id = 0;
        long relation_id = goods.getProd_id();
        //点赞的评论ID（如果是内容点赞此处为0）
        int relation_comment_id = 0;
        OkHttpRequest.getInstance().addCollection(HttpContants.addCollection,
                AppManager.getUserInfo().getUser_id(),
                relation_id,
                class_id,
                relation_comment_id,
                new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if(jsonObject != null){
                                mGoods.setIs_like(1);
                                int collection_num = mGoods.getCollection_num();
                                mGoods.setCollection_num(++collection_num);
                                mGoods.setIs_like(1);
                                adapter.notifyDataSetChanged();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refrashData(PublicRefrash publicRefrash){
        if (publicRefrash != null) {
            if (adapter.getItemCount() >= publicRefrash.getPosition()) {
                Goods goods = publicRefrash.getGoods();
                if(goods == null)return;
                int p = publicRefrash.getPosition();
                if (mList.get(p).getProd_id() == goods.getProd_id()) {
                    mList.get(p).setComment_num(goods.getComment_num());
                    mList.get(p).setCollection_num(goods.getCollection_num());
                    mList.get(p).setIs_like(goods.getIs_like());
                    mList.get(p).setShare_num(goods.getShare_num());
                    adapter.notifyItemChanged(p);
                }

            }
        }
    }
}
